import { connect } from 'react-redux'
import React from 'react'
import ResizeDetector from 'react-resize-detector'
import PropTypes from 'prop-types'
import { canvas as canvasDuck } from 'ducks'
import RootStage from './rootStage'

class LabelBoardView extends React.Component {
  static propTypes = {
    isInitSize: PropTypes.bool.isRequired,
    actionSetWindowSize: PropTypes.func.isRequired,
    actionSetMouseWheel: PropTypes.func.isRequired,
  }

  componentDidMount() {
    this.node.addEventListener('mousewheel', this.handleMousewheel, false)
    window.addEventListener('contextmenu', (e) => {
      e.preventDefault()
      return false
    })
  }

  onResize = (w, h) => {
    const { isInitSize, actionSetWindowSize } = this.props
    if (!isInitSize && w > 0 && h > 0) {
      actionSetWindowSize({ w, h })
    }
  }

  handleMousewheel = (e) => {
    const { actionSetMouseWheel } = this.props
    const value = e.wheelDeltaY * 0.0006666 // 0.0006666 = 1/1500
    actionSetMouseWheel(value)
  }

  render() {
    const { isInitSize } = this.props
    return (
      <div
        ref={(node) => {
          this.node = node
        }}
        style={{
          height: '100%',
          width: '100%',
          backgroundImage:
            'repeating-linear-gradient(0deg, transparent, transparent 7px, rgba(0, 0, 0, 0.2) 1px, transparent 8px), repeating-linear-gradient(90deg, transparent, transparent 7px, rgba(0, 0, 0, 0.2) 1px, transparent 8px)',
        }}
      >
        {isInitSize && <RootStage />}
        <ResizeDetector handleWidth handleHeight onResize={this.onResize} />
      </div>
    )
  }
}

const mapStateToProps = state => ({
  isInitSize: canvasDuck.selectors.isInitSize(state),
})

const mapDispatchToProps = {
  actionSetWindowSize: canvasDuck.creators.actionSetWindowSize,
  actionSetMouseWheel: canvasDuck.creators.actionSetMouseWheel,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(LabelBoardView)
